import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store";

import { Message } from 'element-ui';
import bus from "@/utils/EventBus"

import HomeView from '@/views/Home'
import LoginView from '@/views/Login'
import NotFoundView from '@/views/NotFound'

import DefaultView from "@/views/Home/Default";
import GoodsListView from "@/views/Goods/GoodsList"
import GoodsSearchView from "@/views/Goods/GoodsSearch"

import BannerListView from "@/views/Banner/BannerList"
import BannerShowView from "@/views/Banner/BannerShow"
import BannerAddView from "@/views/Banner/BannerAdd"

import EchartsView from "@/views/Plugins/Echarts"
import EditorView from "@/views/Plugins/Editor"

import AdminListView from "@/views/Admin/AdminList"
import AdminAddView from "@/views/Admin/AdminAdd"

Vue.use(VueRouter)

const routes = [
  // 一级视图中
  {
    path: '/',
    name: 'home',
    component: HomeView,
    // 二级试图 => 放在一级视图的/路由下
    children: [{
      path: "",
      redirect: "/home",
    }, {
      path: "/home",
      name: "defaultHome",
      component: DefaultView,
      meta: {
        role: ["1", "2", "3"]
      },
      label: "首页",
      icon: "",
    }, {
      path: "/admin/list",
      name: "adminList",
      component: AdminListView,
      meta: {
        role: ["1", "2"]
      },
      label: "人员列表",
      icon: "",
      parent: { path: "/admin", name: "admin", label: "人员管理", icon: "" }
    }, {
      path: "/admin/add",
      name: "adminAdd",
      component: AdminAddView,
      meta: {
        role: ["1"]
      },
      label: "人员新增",
      icon: "",
      parent: { path: "/admin", name: "admin", label: "人员管理", icon: "" }
    }, {
      path: "/goods/list",
      name: "goodsList",
      component: GoodsListView,
      meta: {
        role: ["1", "2", "3"]
      },
      label: "商品列表",
      icon: "",
      parent: { path: "/goods", name: "goods", label: "商品管理", icon: "" }  // 自定义数据 => 用于标记公共父级 => 用于生成菜单
    }, {
      path: "/goods/search",
      name: "goodsSearch",
      component: GoodsSearchView,
      meta: {
        role: ["1", "2", "3"]
      },
      label: "商品搜索",
      icon: "",
      parent: { path: "/goods", name: "goods", label: "商品管理", icon: "" }
    }, {
      path: "/banner/show",
      name: "bannerShow",
      component: BannerShowView,
      meta: {
        role: ["1", "2", "3"]
      },
      label: "轮播展示",
      icon: "",
      parent: { path: "/banner", name: "banner", label: "轮播管理", icon: "" }
    }, {
      path: "/banner/list",
      name: "bannerList",
      component: BannerListView,
      meta: {
        role: ["1", "2", "3"]
      },
      label: "轮播列表",
      icon: "",
      parent: { path: "/banner", name: "banner", label: "轮播管理", icon: "" }
    }, {
      path: "/banner/add",
      name: "bannerAdd",
      component: BannerAddView,
      meta: {
        role: ["1", "2"]
      },
      label: "轮播新增",
      icon: "",
      parent: { path: "/banner", name: "banner", label: "轮播管理", icon: "" }
    }, {
      path: "/plugins/echarts",
      name: "pluginsEcharts",
      component: EchartsView,
      meta: {
        role: ["1", "2", "3"]
      },
      label: "Echarts",
      icon: "",
      parent: { path: "/plugins", name: "plugins", label: "插件学习", icon: "" }
    }, {
      path: "/plugins/editor",
      name: "pluginsEditor",
      component: EditorView,
      meta: {
        role: ["1", "2", "3"]
      },
      label: "富文本",
      icon: "",
      parent: { path: "/plugins", name: "plugins", label: "插件学习", icon: "" }
    }],
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/about',
    name: 'about',
    component: () => import(/* webpackChunkName: "about" */ '../views/About')
  },
  {
    path: '/404',
    name: 'notfound',
    component: NotFoundView
  },
  {
    path: "*",
    redirect: "/404",
  }
]


function transformRoutesToMenu(routes) {
  var route = routes[0]; //找到主页的相关配置(菜单在主页中生成)
  var children = route.children;
  var mapMenu = {
    // defaultHome:{path,name,label,icon},  一级菜单,可以直接对于name 属性存储到对象中
    // goods:{path,name,label,icon,children:[{path,name,label,icon}]}, 二级菜单第一次放(对应的一级菜单不存在) => 1. 先生成一级菜单 对应一级菜单name属性放到mapMenu 2. 将二级菜单的配置,放到一级菜单的children数据中
  }

  children.forEach(item => {  // 二级视图中的每一个配置
    if (item.path == "") return false;  // 跳过默认
    else if (!Object.hasOwn(item, "parent")) {  // 一级菜单
      let { path, name, label, icon, meta } = item;
      let menu = { path, name, label, icon, meta };
      mapMenu[item.name] = menu;
    } else if (Object.hasOwn(item, "parent")) {  // 有parent => 二级菜单
      let parent = item.parent; // 二级菜单对应的一级配置
      // mapMenu[parent.name] = parent;

      // 以 /goods/list  和 /goods/search 为例
      // 第一次放  =>
      // let {path,name,label,icon} = item;  // 二级菜单相关配置
      // let menu = {path,name,label,icon};
      // parent.children = [menu]

      // 第二次放
      // parent.children.push(menu);

      if (!Object.hasOwn(mapMenu, parent.name)) {  // 这个一级菜单是第一次创建
        mapMenu[parent.name] = parent; // 将一级菜单放到mapMenu中

        parent.children = [];  // 先新增children => 数组 => 用于存储二级菜单
        let { path, name, label, icon, meta } = item;  // 二级菜单相关配置
        let menu = { path, name, label, icon, meta };
        parent.children.push(menu);

      } else {  // 对于的一级菜单已经创建
        let { path, name, label, icon } = item;  // 二级菜单相关配置
        let menu = { path, name, label, icon };
        mapMenu[parent.name].children.push(menu);
      }

    }

  })

  // return mapMenu;
  return Object.values(mapMenu);
}

export let menus = transformRoutesToMenu(routes);
// console.log(JSON.stringify(menus));



const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})


let whiteList = ["/login", "/404"]; // 白名单
let count = 0;   // 变量

router.beforeEach(function (to, from, next) {

  // 1. 判断白名单
  // if (!whiteList.includes(to.path)) {  // 不是白名单中的路由路径
    

    // console.log("每次路由跳转时获取本地token数据 同步到vuex");
    // store.dispatch("getAndUpdateAuthorityInfo");// 在页面跳转时 => 解析localStorge数据  => 同步到vuex


    if (count == 0) {
      console.log("页面初次加载或者刷新时执行一次 =>  同步到vuex");
      store.dispatch("getAndUpdateAuthorityInfo");// 在页面跳转时 => 解析localStorge数据  => 同步到vuex
      count++;
      // bus.$emit("loadingStart");
    }
    next();
  // } else {  // 是白名单中的路由路径
  //   next();
  // }

})

router.beforeEach(function (to, from, next) {
  console.log("从哪来", from);
  console.log("到哪去", to);

  // 1. 区分那些页面要登录  那些页面不用登录

  // 2. 判断用户是否登录  => (前提:页面需要用户登录)

  // 3. 在路由跳转时,判断是否是当前登录用户能访问的 checkedkeys= []   (前提:当前用户要登录)
  // 是 => 跳转
  // 不是 => 拒绝

  // 1. 判断白名单
  if (!whiteList.includes(to.path)) {  // 不是白名单中的路由路径

    // 获取store中的数据 => 问题: 路由跳转在主页面加载执行之前  =>   store.dispatch("getAndUpdateAuthorityInfo")提到当前中间件之前执行
    console.log("路由跳转时获取store数据adminname:", store.state.userInfo.adminname);
    console.log("路由跳转时获取store数据checkedkeys:", store.state.userInfo.checkedkeys);
    console.log("路由跳转时获取store数据isLogin:", store.getters.isLogin);

    // 2. 判断用户是否登录  => (前提:页面需要用户登录)
    if (store.getters.isLogin) {   // isLogin == true => 已经登录
      let checkedkeys = store.state.userInfo.checkedkeys;
      let role = store.state.userInfo.role;

      if (role == 1) {  // 如果是超级管理员 直接访问 => admin中没有checkedkeys
        next();
      } else {
        // 3.  要跳转的路由是否是当前用户可以访问的
        if (checkedkeys.includes(to.path)) {  //    是 => 跳转
          next();
        } else {
          next(false);
          Message({
            message: "你在想什么呢!",
            type: "warning",
          })
        }

      }

    





    } else {  // isLogin == false;  // 没有登录 => 去登录
      router.push({
        path: "/login",
        query: { ReturnUrl: router.currentRoute.fullPath }
      })
      Message({
        message: "您还没有登录,请登录!",
        type: "warning",
      })
      // next();
    }

  } else {  // 是白名单中的路由路径
    next();
  }



})

export default router
